<template>
    <view class="swiperCon">
        <scroll-view class="scrollViews" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true">
            <view v-for="(items, index) in getlineNode" :key="index">
                <view class="swiper-item uni-bg-red">
                    <texts v-if="items.type && items.type == 'text'" :text="items.name"></texts>
                    <lines ref="linesRef" v-else :items="items" @register="childEvent"></lines>
                </view>
            </view>
        </scroll-view>
        <!-- <linesda></linesda> -->
    </view>
</template>

<script>
import texts from '../texts.vue'
import lines from './lineCes.vue'
import { mapGetters } from 'vuex';
export default {
    name: 'lineoin',
    components: {
        texts,
        lines,
    },
    computed: {
        getlineNode() {
            return this.$store.getters.getlineNode;
        },
        ...mapGetters({
            // 假设Vuex store中有一个名为'myData'的状态
            myGetterData: 'getreceiveUserName',
        }),
    },
    data: function () {
        return {
            scrollTop: 0,
            data: [],
            registeredMethods: new Map()      // 存储子组件方法
        }
    },
    mounted() {
        // this.start()
        this.init()
    },
    watch: {
        myGetterData(newVal) {
            // 当myGetterData变化时执行的逻辑
            console.log(newVal.lineIds,newVal.lineIds.split(','), '我是阿达懒得')
            const dataName = newVal.message.split('|')
            const dataArray = newVal.lineIds.split(',')
            // 还剩余多少站
            const dataindexs = newVal.indexs.split(',')
            // 下标数据
            const datacurrentIndex = newVal.currentIndex.split(',')

            console.log(dataName, dataArray, dataindexs, datacurrentIndex, '我字了')

            const processTransitData = (ids, texts, distances, stationIndexes) => {
                const resultMap = new Map();

                ids.forEach((id, index) => {
                    const entry = {
                        text: texts[index],
                        distance: parseInt(distances[index], 10),
                        stationIndex: parseInt(stationIndexes[index] - 1, 10),
                    };
                    console.log(id,'我是id521')
                    if (!resultMap.has(id)) {
                        resultMap.set(id, []);
                    }
                    resultMap.get(id).push(entry);
                });

                // 动态选择逻辑
                const finalResult = Array.from(resultMap).map(([id, entries]) => {
                    // 按distance升序排序
                    entries.sort((a, b) => a.distance - b.distance);

                    const pamras = processEntries(entries)
                    if (pamras.distance == 999) {
                        pamras.name = pamras.text
                    } else if (pamras.distance == 1) {
                        pamras.name = "即将进站"
                    } else {
                        pamras.name = '距本站' + pamras.distance + '站'
                    }

                    console.log(id,'我是id吗帖子')

                    return {
                        code: id,
                        display: pamras,
                        current: entries.filter(item => {
                            return item.stationIndex != 998
                        }),
                        allData: entries  // 保留完整数据供参考

                    };
                });
                return finalResult
            };

            const formattedData = processTransitData(
                dataArray,      // ID数组
                dataName, // 显示文本数组
                dataindexs,    // 距离数组
                datacurrentIndex // 站点下标数组
            );


            function processEntries(targetEntry) {
                // 输入验证：空数组或非数组直接返回 null
                if (!Array.isArray(targetEntry) || targetEntry.length === 0) {
                    return {};
                }

                // 单个元素直接返回
                if (targetEntry.length === 1) {
                    return targetEntry[0];
                }

                // 第一个元素的 distance 不为 0，直接返回
                if (targetEntry[0].distance != 999) {
                    return targetEntry[0];
                }

                // 第一个元素的 distance 为 0，寻找后续第一个非 0 的元素
                for (let i = 1; i < targetEntry.length; i++) {
                    if (targetEntry[i].distance != 999) {
                        return targetEntry[i];
                    }
                }

                // 如果所有元素的 distance 均为 0，返回第一个元素
                return targetEntry[0];
            }

            console.log(formattedData, 'wi是大')

            for (let index = 0; index < formattedData.length; index++) {
                const elemen = formattedData[index];
                console.log(elemen, '我是阿达懒得')
                this.callAllMethods(elemen)
            }

            console.log(dataName, dataArray, dataindexs, datacurrentIndex, '我字了')
        },
    },
    methods: {
        init() {
            if (this.getlineNode.length <= 4) return;
            const query = uni.createSelectorQuery().in(this);
            // 数据长度检查
            // 单次获取元素高度并缓存
            query.select('.swiper-item').boundingClientRect(data => {
                if (!data || data.height === 0) return;

                // 缓存元素高度
                const itemHeight = data.height;

                // 重置初始状态
                this.current = 0;
                this.scrollTop = 0;

                // 配置滚动间隔
                const interval = this.$store.state.StationConfig.stopSecond;

                this.intervalId = setInterval(() => {
                    // 边界检测（使用 >= 更安全）
                    if (this.current >= this.getlineNode.length - 4) {
                        this.current = 0;
                        this.scrollTop = 0;
                    } else {
                        // 使用缓存高度计算
                        this.scrollTop = this.current * itemHeight;
                    }
                    console.log(this.scrollTop, '我滚动了嘛123')
                    this.current++;
                    // 强制视图更新（根据框架需要）
                    // this.$forceUpdate(); 
                }, interval);
            }).exec();
            // if (this.getlineNode.length > 4) {
            // 	this.intervalId = setInterval(() => {
            // 		if (this.current >= this.getlineNode.length - 4) {
            // 			this.current = 0;
            // 			this.scrollTop = 0;
            // 		} else {
            // 			query.select('.swiper-item').boundingClientRect(data => {
            // 				this.scrollTop = this.current * data.height;
            // 				console.log(this.scrollTop, '我是挂牌督啊')
            // 			}).exec();
            // 			this.current++;
            // 		}
            // 	}, this.$store.state.StationConfig.stopSecond);
            // }
        },

        childEvent({ id, method }) {
            console.log('我开始设置了')
            this.registeredMethods.set(id, method)
        },
        // 调用所有注册方法
        callAllMethods(params) {
            // this.registeredMethods.forEach(method => method())
            const method = this.registeredMethods.get(params.code)
            method?.(params)
        }
    }
};
</script>

<style lang="scss" scoped>
.swiperCon {
    flex: 1;
    height: 100%;
    overflow: hidden;
    position: relative;

    .scrollViews {
        height: 100%;

        // .uni-scroll-view {
        // 	height: 100%;
        // }
    }
}
</style>